package twitter.RequestHandler;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.w3c.dom.Document;

import twitter.RequestParser.FrontendRequestParser;
import twitter.TwitterLibrary.HTTPHelper;
import twitter.TwitterLibrary.Utility;
/******************************************************
 * this class is designed for handles the request that the front end server receives
 * @author fang
 *
 */
public class FrontendHttpRequestHandler extends HTTPRequestHandler{
	private HTTPHelper httpHelper;
	private FrontendRequestParser frontendParser;
	
	private String end;
	/************************************
	 * Class constructor
	 * @param end :the end message of all the requests that the front end server receivers
	 * @param rwl :the read write lock
	 */
	public FrontendHttpRequestHandler(ReentrantReadWriteLock rwl,Utility utility) {
		super(rwl,utility);
		httpHelper=new HTTPHelper();
		this.end=end;
		// TODO Auto-generated constructor stub
	}
	/*******************************************
	 * this method is used for write http request message
	 * @param httpOutput:PrintWriter output
	 * @param command: the message needs to be sent in the http message
	 * @param number: specify the type of http message
	 */
	private void writeHttp(PrintWriter httpOutput, String command, int number) {
		httpOutput.write(httpHelper.construct_http_header(number));
		httpOutput.write(httpHelper.httpMessage(number));
		httpOutput.write(command);
		httpOutput.flush();
	}
	/*************************************
	 * set the cache for this front end http parser
	 * @param versionCache: stores all the version information
	 * @param tagCache:stores all the hashtag information
	 */
	public void setCache(HashMap<String, Document> versionCache,
			HashMap<String, Integer> tagCache) {

		frontendParser=new FrontendRequestParser(end,rwl,utility);
		frontendParser.setCache(versionCache, tagCache);
	}
	/**************************************************
	 * parse the front end http request
	 */
	public void parseHttpRequest(String httpInput, PrintWriter httpOutput) {

	
		System.out.println("in the parsehttprequest of frontendserver "
				+ httpInput);

		int start = 0;
		int end = 0;
		String path = "";
		start = httpInput.indexOf(" ");
		end = httpInput.indexOf("=");

		String query = "";

		if (!httpInput.contains("HTTP/1.1")) {

			writeHttp(httpOutput, "", 505);
			return;
		}

		if ((httpInput.startsWith("DELETE")) || (httpInput.startsWith("PUT"))) {

			writeHttp(httpOutput, "", 501);
			return;
		}
		if (httpInput.startsWith("GET")) {

			if ((start > 0) && (end > 0)) {
				path = httpInput.substring(start + 1, end);

				if (!httpInput.contains("?q=")) {

					writeHttp(httpOutput, "", 400);
					return;
				} else if (path.equals("/search?q")) {

					query = httpInput.substring(httpInput.indexOf("=") + 1,
							httpInput.indexOf(" ", end));

					String response = "";
					try {
						response = frontendParser.responseGet(query);
					} catch (NullPointerException e) {
						writeHttp(httpOutput, "", 500);
						return;
					}
					if (response.trim().equals("error")) {
						writeHttp(httpOutput, "", 500);
						return;
					} else {

						writeHttp(httpOutput, response, 200);
						return;
					}

				} else if (!path.equals("/search?q")) {
					writeHttp(httpOutput, "", 404);
					return;
				} else {
					writeHttp(httpOutput, "", 400);
					return;
				}
			} else {
				writeHttp(httpOutput, "", 400);
				return;
			}

		} else if (httpInput.startsWith("POST")) {
			if ((start > 0) && (end > 0)) {
				path = httpInput.substring(start + 1, end);

				if (!path.contains("/status/update?")) {
					writeHttp(httpOutput, "", 404);
					return;
				} else if (!path.equals("/status/update?status")) {

					writeHttp(httpOutput, "", 400);
					return;
				} else if (path.equals("/status/update?status")) {
					String status = httpInput.substring(
							httpInput.indexOf("=") + 1, httpInput.indexOf(" ",
									end));
					String postResult = "";
					try {
						postResult = frontendParser.responsePost(status);
					} catch (java.lang.NullPointerException e) {
						writeHttp(httpOutput, "", 500);
						return;
					}
					if (postResult.equals("success")) {

						writeHttp(httpOutput, "", 204);
						return;
					} else {

						writeHttp(httpOutput, "", 500);
						return;
					}

				} else {
					writeHttp(httpOutput, "", 400);
					return;
				}

			} else {

				writeHttp(httpOutput, "", 400);
				return;
			}

		}

	}
}
